import { intl, resDataFilter } from '@/utils';
import { msgInfo } from '@/utils/msg';
import notify from 'devextreme/ui/notify';
import { useCallback, useRef, useState } from 'react';
import { useModel } from 'umi';
import { LayoutB } from '~/public/cpas-ui';
import ErrorBounced from '../components/ErrorBounced';
import ErrorBouncedChangeName from '../components/ErrorBounced/errorBouncedChangeName';
import MoveToPhase from './components/MoveToPhase';
import TemplateDialog from './components/TemplateDialog';
import type { MenuItemClickEvent, PhaseItem } from './data';
import './index.less';
import style from './index.less';
import PaperTable from './PaperTable';
import { BatReplacePopup } from './PaperTable/components/BatReplace';
import PhaseTree from './PhaseTree';
import {
  getApiParperAdd,
  getApiParperReplace,
  getPhaseTreeUpdate,
  PaperMobile,
  templateLibraryReplace,
} from './service';

export const modalExtensions = [
  'doc',
  'docx',
  'xls',
  'xlsx',
  'jpg',
  'gif',
  'bmp',
  'png',
  'txt',
  'pdf',
  'rar',
  'rar4',
  'zip',
  'mp3',
  'mp4',
  'xlsm',
  'xltm',
  'xlam',
  'xlsb',
  'csv',
];

const AuditPaper = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh, zcbfid } = initialState?.curPart as API.CurPart;
  const { username, usercode } = initialState?.curUser as API.CurUser;
  const [curPhase, setCurPhase] = useState<PhaseItem & any>({});
  const errorBouncedRef = useRef<any>(); //
  const errorBouncedRefChangeNameRef = useRef<any>(); //
  const paperTableRef = useRef<any>(); // 底稿列表
  const paperPhaseTreeRef = useRef<any>(); // 阶段列表
  const moveToPhaseRef = useRef<any>(); // 移动到
  const tplDialogRef = useRef<any>(); // 模板
  // const tplReplaceRef = useRef<any>()
  const [isNeedBatReplace, setIsNeedBatReplace] = useState<boolean>(false); //是否需要批量替换
  const batReplacePopupRef = useRef<any>(); //批量替换是引用

  /**
   * 显示批量替换底稿
   * @param dgnd
   * @param refreshCb
   * @returns
   */
  async function showBatReplaceWindow(dgnd: string, refreshCb: any) {
    const retData = await window.electronComponents.openDirectoryDialog();
    if (retData.canceled) return;
    msgInfo(intl('paper.loadingBatReplace', '文件夹批量替换加载中,请稍候...'));
    setIsNeedBatReplace(true);
    batReplacePopupRef.current?.show({
      title: intl('paper.replaceFromFolder', '从文件夹批量替换'),
      filePath: retData.filePaths[0],
      dgnd: dgnd,
      okCallback: (retData: any) => {
        refreshCb && refreshCb();
      },
    });
  }

  // 底稿列表菜单 单击事件(e.from = dg)
  const onDGMenuItemClieck = useCallback((rowData: MenuItemClickEvent) => {
    let rowDgnd = '';
    const rowDgid = rowData.data.dgid;
    let tempRowDgids: any[] = [];
    if (Array.isArray(rowData.data)) {
      tempRowDgids = rowData.data.map((item: any) => item.dgid);
      rowDgnd = rowData.data[0].dgnd;
    } else {
      tempRowDgids = [rowData.data.dgid];
      rowDgnd = rowData.data.dgnd;
    }

    switch (rowData.itemID) {
      // 移动到
      case 'moveToPhase':
        // 将选中的底稿移动到指定阶段
        moveToPhaseRef.current?.show({
          args: {
            dbname,
            dgnd: rowDgnd,
          },
          okCallback: async (value: any) => {
            moveToPhaseRef.current?.close();
            const r = await PaperMobile('0', value.id, tempRowDgids, sjxmbh, username, dbname);
            if (r.success) {
              paperTableRef.current.refresh();
              notify('移动成功', 'success', 2000);
              // const resFilter = resDataFilter(r.data);
              // if (resFilter.success) {
              //   const { reDataArr } = resFilter;
              //   if (reDataArr.tempError.length) {
              //     return errorBouncedRef.current.show({
              //       args: {
              //         codes: true,
              //         data: reDataArr.tempError,
              //       },
              //     });
              //   }
              //   notify('移动成功', 'success', 3000);
              //   paperTableRef.current.refresh();
              // } else {
              //   paperTableRef.current.refresh();
              //   notify('移动成功', 'success', 2000);
              // }
            } else {
              notify('保存失败', 'error', 2000);
            }
          },
        });
        break;
      // 从模板库中替换
      case 'replaceFromTemplate':
        tplDialogRef.current.show({
          args: {
            title: '从模板库中替换',
            codes: true,
            isMultiple: false,
          },
          okCallback: async (e: any, Title: string) => {
            console.log(e, Title);
            const dgid = rowDgid;
            const distPath = sjxmbh + '/' + zcbfid;
            const res = await templateLibraryReplace(dbname, e, Title, dgid, username, distPath);
            if (res.success) {
              const resFilter = resDataFilter(res.data);
              if (resFilter.success) {
                const { reDataArr } = resFilter;
                if (reDataArr.tempError.length) {
                  return errorBouncedRef.current.show({
                    args: {
                      codes: true,
                      data: reDataArr.tempError,
                    },
                  });
                }
                notify('移动成功', 'success', 3000);
                paperTableRef.current.refresh();
              } else {
                notify('替换失败', 'error', 2000);
              }
            } else {
              notify('替换失败', 'error', 2000);
            }
          },
        });
        break;
      case 'replaceFromFolder': {
        showBatReplaceWindow(rowDgnd, paperTableRef.current.refresh);
        break;
      }
      default:
        break;
    }
  }, []);

  const refreshTable = () => {
    paperTableRef.current.refresh();
  };

  const fromFile_fun = async (dgnd: any, jdmc: any, dgDataArr: any, tmpPathFolder?: string) => {
    // 记录是否有错误 - lzx
    const res = await getPhaseTreeUpdate(username, dgnd, jdmc, sjxmbh, zcbfid, dbname, dgDataArr);
    if (res.success) {
      if (res.errorList.length) {
        return errorBouncedRefChangeNameRef.current.show({
          args: {
            codes: true,
            dbname,
            dgnd,
            pupopType: 'dg',
            data: res.errorList,
            valueSource: ''
          },
          okCallback: async (tempData: any[]) => {
            // console.log(tempData, '@@@ okCallback');
            if (tempData.length > 0) {
              const resUpdate = await getPhaseTreeUpdate(
                username,
                dgnd,
                jdmc,
                sjxmbh,
                zcbfid,
                dbname,
                tempData,
              );
              if (resUpdate.success) {
                paperTableRef.current.refresh();
              } else {
                notify('导入失败', 'error', 3000);
              }
            } else {
              paperTableRef.current.refresh();
            }
          },
          cancelCallback: () => {
            paperTableRef.current.refresh();
          },
        });
      }
      notify('导入成功', 'success', 3000);
      paperTableRef.current.refresh();

    } else {
      notify('导入失败', 'error', 2000);
    }
  };

  // 阶段菜单单击事件
  const onJDMenuItemClick = useCallback(async (item: MenuItemClickEvent) => {
    const dgnd = item.data.dgnd;
    const jdid = item.data.id;
    const jdmc = item.data.text;
    switch (item.itemID) {
      // 模板新建
      case 'fromTemplte':
        tplDialogRef.current.show({
          args: {
            title: '从底稿模板新建',
            codes: true,
            isMultiple: true,
          },
          okCallback: async (e: any, Title: string) => {
            const dgmcs = e.map((item: { id: any }) => {
              return item.id;
            });
            const dgSyhs = e.map((item: { syh: any }) => {
              return item.syh;
            });

            console.log(dgmcs, e, '@@@');

            const r = await getApiParperAdd(
              dbname,
              zcbfid,
              sjxmbh,
              jdid,
              dgnd,
              dgmcs,
              dgSyhs,
              Title,
              username,
            );
            if (r.success) {
              if (r.data.length) {
                return errorBouncedRefChangeNameRef.current.show({
                  args: {
                    codes: true,
                    dbname,
                    dgnd,
                    pupopType: 'dg',
                    data: r.data,
                    valueSource: 'payload'
                  },
                  okCallback: async (tempData: any[]) => {
                    console.log(tempData, '@@@ okCallback');
                    if (tempData.length > 0) {
                      const resUpdate = await getApiParperAdd(
                        dbname,
                        zcbfid,
                        sjxmbh,
                        jdid,
                        dgnd,
                        dgmcs,
                        dgSyhs,
                        Title,
                        username,
                        tempData[0],
                        tempData[1],
                      );
                      if (resUpdate.success) {
                        paperTableRef.current.refresh();
                      } else {
                        notify('导入失败', 'error', 3000);
                      }
                    } else {
                      paperTableRef.current.refresh();
                    }
                  },
                  cancelCallback: () => {
                    paperTableRef.current.refresh();
                  },
                });
              }
            } else {
              notify('从底稿模板新建失败', 'error', 2000);
            }
          },
        });
        break;
      // 从模板替换
      case 'reFromTemplte':
        tplDialogRef.current.show({
          args: {
            title: '从模板替换',
            codes: true,
            isMultiple: true,
          },
          okCallback: async (e: any, Title: string) => {
            const dgmcs = e.map((item: { id: any }) => {
              return item.id;
            });
            const dgsyhs = e.map((item: { syh: any }) => {
              return item.syh;
            });
            const res = await getApiParperReplace(
              dbname,
              zcbfid,
              sjxmbh,
              jdid,
              dgnd,
              dgmcs,
              dgsyhs,
              Title,
              username,
            );
            if (res.success) {
              const resFilter = resDataFilter(res.data);
              if (resFilter.success) {
                const { reDataArr } = resFilter;
                if (reDataArr.tempError.length) {
                  return errorBouncedRef.current.show({
                    args: {
                      codes: true,
                      data: reDataArr.tempError,
                    },
                  });
                }
                notify('从模板替换成功', 'success', 3000);
                paperTableRef.current.refresh();
              } else {
                notify('从模板替换失败', 'error', 2000);
              }
            } else {
              notify('从模板替换失败', 'error', 2000);
            }
          },
        });
        break;
      // 从外部导入
      case 'fromFile':
        const dgData = await window.electronComponents.openDialog({
          properties: ['openFile', 'multiSelections'],
          filters: [
            {
              name: 'Office Files',
              extensions: modalExtensions,
            },
            { name: 'all', extensions: ['*'] },
          ],
        });
        if (!dgData.canceled) {
          fromFile_fun(dgnd, jdmc, dgData.filePaths);
        }
        break;
      case 'replaceFromFolder': {
        showBatReplaceWindow(dgnd, paperTableRef.current.refresh);
        break;
      }
      default:
        break;
    }
  }, []);

  // 刷新底稿列表执行
  function paperPhaseTableReload(value: boolean) {
    if (value) {
      paperTableRef.current.refresh();
      setCurPhase({});
    }
  }
  // 刷新阶段列表执行
  async function paperPhaseTreeReload(value: boolean) {
    if (value) {
      await paperPhaseTreeRef.current.refresh();
    }
  }
  const selectTreeNode = (item: any) => {
    // console.log(item, '@@@');
    setCurPhase(item);
  };

  function leftContainer() {
    return (
      <div className={style.PaperLeftBox}>
        <PhaseTree
          ref={paperPhaseTreeRef}
          canEdit={true}
          fromFile_fun={fromFile_fun}
          refreshTable={refreshTable}
          treeItemClick={selectTreeNode}
          onMenuItemClieck={onJDMenuItemClick}
          paperPhaseTableReload={paperPhaseTableReload}
        />
      </div>
    );
  }

  function rightContainer() {
    return (
      <div className={style.PaperRightBox}>
        <PaperTable
          ref={paperTableRef}
          curPhase={curPhase}
          onMenuItemClieck={onDGMenuItemClieck}
          paperPhaseTreeReload={paperPhaseTreeReload}
        />
      </div>
    );
  }

  return (
    <>
      <div
        className="audit-paper"
        style={{
          height: 'calc(100vh - 54px)',
          display: 'flex',
          width: '100%',
        }}
      >
        <LayoutB
          rowSize={['10%', '350px', '68%']}
          leftSlot={leftContainer()}
          rightSlot={rightContainer()}
        />
      </div>
      <ErrorBounced ref={errorBouncedRef} />
      <ErrorBouncedChangeName ref={errorBouncedRefChangeNameRef} />
      <MoveToPhase ref={moveToPhaseRef} />
      <TemplateDialog ref={tplDialogRef} />

      {/* 批量替换 */}
      {/* {isNeedBatReplace && <BatReplacePopup ref={batReplacePopupRef} />} */}
      <BatReplacePopup ref={batReplacePopupRef} />
    </>
  );
};

export default AuditPaper;
